// Initalise display options
// Vars added in 1.1.0
if (!localStorage.popup_dataCap) {

	localStorage.popup_dataCap = 0;
	localStorage.tooltip_dataCap = 0;

	localStorage.popup_localDataUsed = 0;
	localStorage.tooltip_localDataUsed = 0;

	localStorage.popup_standardDataUsed = 0;
	localStorage.tooltip_standardDataUsed = 0;

	localStorage.popup_standardDataLeft = 1;
	localStorage.tooltip_standardDataLeft = 1;

	localStorage.popup_percentageBar = 1;
	localStorage.tooltip_percentageBar = 0;

	localStorage.popup_costToDate = 1;
	localStorage.tooltip_costToDate = 1;

	localStorage.popup_timeRemaining = 1;
	localStorage.tooltip_timeRemaining = 1;

	localStorage.popup_timeLastUpdated = 1;
	localStorage.tooltip_timeLastUpdated = 0;

	localStorage.popup_xnet = 0;
	localStorage.popup_webmail = 0;
	localStorage.popup_networkStatus = 0;
	localStorage.popup_speedTest = 0;
	localStorage.popup_support = 0;
	localStorage.popup_viewBill = 0;
	localStorage.popup_vfxPortal = 0;

	localStorage.popup_xmlDataFile = 0;
}

// Vars added in 1.2.0
if (!localStorage.custom_cap) {
	localStorage.custom_cap = 1024;
	localStorage.popup_speedtestDotNet = 0;
	localStorage.popup_pingtestDotNet = 0;
	localStorage.popup_xport = 0;
	localStorage.cap_original = 0;

	localStorage.popup_dailyAverage = 1;
	localStorage.tooltip_dailyAverage = 0;

	localStorage.popup_monthlyEstimate = 1;
	localStorage.tooltip_monthlyEstimate = 0;
}

// Vars added in 1.2.2
if (!localStorage.popup_freeDataUsed) {
	localStorage.popup_freeDataUsed = 0;
	localStorage.tooltip_freeDataUsed = 0;
}

// Vars added in 1.3.0
if (!localStorage.popup_usageHistory) {
	localStorage.popup_usageHistory = 1;
}

// Vars added in 1.4.0
if (!localStorage.popup_dataUsed) {
	localStorage.popup_dataUsed = 1;
	localStorage.tooltip_dataUsed = 1;
	localStorage.popup_targetDailyAverage = 1;
	localStorage.tooltip_targetDailyAverage = 0;
}

// Show update message if needed
if (localStorage.currentVersion && localStorage.currentVersion != "1.4.0") {
	webkitNotifications.createNotification(
		'green-x-48.png',
		'Your Xnet Usage Monitor has been updated to v1.4.0.',
		'Two new options added: "Total data used" and "Suggested daily usage".\nAlso, percentages and estimates are now calculated based on Total Data Used instead of Standard Data Used. Check out the Options page for more info.'
	).show();
}

localStorage.currentVersion = "1.4.0";

// Apply browser action title tooltip with data info
function updateTooltip() {
	var tooltip = '';

	// Data cap
	if (localStorage.tooltip_dataCap == 1) {
		var dataCap = localStorage.cap == "0" ? "None" : number_format(parseFloat(localStorage.cap) / 1024, 2)+" GB";
		tooltip += 'Data cap: '+dataCap+'\n';
	}

	// Local data used
	if (localStorage.tooltip_localDataUsed == 1) {
		tooltip += 'Local data used: '+number_format((parseFloat(localStorage.rxlocal)+parseFloat(localStorage.txlocal)) / 1024, 2)+" GB\n";
	}

	// Free data used
	if (localStorage.tooltip_freeDataUsed == 1) {
		tooltip += 'Free data used: '+number_format((parseFloat(localStorage.freedataused)) / 1024, 2)+" GB\n";
	}

	// Standard data used
	if (localStorage.tooltip_standardDataUsed == 1) {
		tooltip += 'Standard data used: '+number_format(parseFloat(localStorage.total) / 1024, 2)+" GB\n";
	}

	var combinedTotal = parseFloat(localStorage.total) + parseFloat(localStorage.freedataused);
	
	// Total data used
	if (localStorage.tooltip_dataUsed == 1) {
		var dataUsedText = number_format(combinedTotal / 1024, 2)+" GB";
		var dataUsedDescription = localStorage.tooltip_localDataUsed == 1 || localStorage.tooltip_freeDataUsed == 1 || localStorage.tooltip_standardDataUsed == 1 ? 'Total data used:' : 'Data used:';
		tooltip += dataUsedDescription + ' ' + dataUsedText + '\n';
	}
	
	// Data left
	if (localStorage.tooltip_standardDataLeft == 1) {
		var standardDataLeftText = 'Data remaining:';
		if (localStorage.cap == "0") {
			var standardDataLeft = "N/A";
		} else {
			if (combinedTotal >= parseFloat(localStorage.cap)) {
				var standardDataLeft = "0.00 GB";
			} else {
				var standardDataLeft = number_format((parseFloat(localStorage.cap)-combinedTotal) / 1024, 2)+" GB";
			}
		}
		tooltip += standardDataLeftText+' '+standardDataLeft+'\n';
	}

	var daysPassed = ( parseFloat(date("U")) - parseFloat(mktime(0,0,0,date("n"),1)) ) / (60 * 60 * 24);
	var avg = combinedTotal / daysPassed;
	avg = number_format(avg / 1024, 2);

	// Daily average
	if (localStorage.tooltip_dailyAverage == 1) {
		tooltip += 'Average daily usage: '+avg+' GB\n';
	}

	// Monthly estimate
	if (localStorage.tooltip_monthlyEstimate == 1) {
		var daysThisMonth = ( parseFloat(mktime(0,0,0,parseFloat(date("n"))+1,1)) - parseFloat(mktime(0,0,0,date("n"),1)) ) / (60 * 60 * 24);
		tooltip += 'Monthly estimate: '+(number_format(daysThisMonth*avg,2))+' GB\n';
	}
	
	// Target daily average
	if (localStorage.tooltip_targetDailyAverage == 1) {
		var cap = parseFloat(localStorage.cap);
		if (cap > 0) {
			var dataRemaining = 0;
			var targetDailyUsage = 0;
			if (combinedTotal < cap) {
				dataRemaining = (cap-combinedTotal) / 1024;
				var nextMonth = parseFloat(mktime(0, 0, 0, parseInt(date('n'))+1, 1));
				var daysRemaining = (nextMonth - parseFloat(date('U'))) / (60 * 60 * 24);
				targetDailyUsage = dataRemaining / daysRemaining;
				if (targetDailyUsage > dataRemaining) {
					targetDailyUsage = dataRemaining;
				}
			}
			tooltip += 'Suggested daily usage: ' + number_format(targetDailyUsage, 2) +' GB\n';
		} else {
			tooltip += 'Suggested daily usage: N/A\n';
		}
	}

	// Percentage bar
	if (localStorage.tooltip_percentageBar == 1) {
		var percentage = localStorage.cap == 0 ? "Allowance used: N/A (no data cap set!)" : "Allowance used: " + Math.round((combinedTotal / parseFloat(localStorage.cap)) * 100) + "%";
		tooltip += percentage+'\n';
	}

	// Cost to date
	if (localStorage.tooltip_costToDate == 1) {
		tooltip += 'Cost to date: $'+localStorage.bpc+'\n';
	}

	// Time remaining
	if (localStorage.tooltip_timeRemaining == 1) {
		var nextMonthTimestamp = parseFloat(mktime(0,0,0, parseFloat(date("n"))+1, 1, date("Y")));
		var nowTimestamp = parseFloat(date("U"));
		var secondsRemaining = nextMonthTimestamp - nowTimestamp;
		var timeRemainingText = '';
		if (secondsRemaining > 60 * 60 * 24) {
			var daysLeft = Math.floor(secondsRemaining / (60 * 60 * 24));
			timeRemainingText = daysLeft + (daysLeft == 1 ? " day" : " days");
		} else {
			var hoursRemaining = Math.floor(secondsRemaining / (60 * 60));
			timeRemainingText = hoursRemaining == 0 ? '&lt; 1 hour' : hoursRemaining + (hoursRemaining == 1 ? ' hour' : ' hours');
		}
		tooltip += 'Time left: '+timeRemainingText+'\n';
	}

	// Last updated
	if (localStorage.tooltip_timeLastUpdated == 1) {
		tooltip += 'Last updated: '+date("j M @ g:i a", strtotime(localStorage.lastupdate));
	}

	chrome.browserAction.setTitle({title:tooltip});
}

// Fetch the XML data file from Xnet's server and save the data to local storage
function updateUsage() {

	// If user has their details saved...
	if (localStorage.username && localStorage.password) {

		// Get the XML file
		$.ajax({
			type: "GET",
			url: "https://api.xport.co.nz/usage/?username="+localStorage.username+";token="+localStorage.password,
			dataType: "xml",
			timeout: 5000, // sets timeout to 5 seconds

			// If we've retrieved it successfully...
			success: function(data){

				// Clear any "!" badge text
				chrome.browserAction.setBadgeText({text:""});

				// Enable the popup page
				chrome.browserAction.setPopup({popup:"xnet.usage.html"});

				// Add every XML tag and value to localStorage
				var $trafficUsageResponse = $("trafficUsageResponse",data);
				$trafficUsageResponse.children().each(function(){
					localStorage[$(this).get(0).tagName] = $(this).text();
		        });

		        // If XML file has an error...
		        if (localStorage.errstr && localStorage.errstr.length) {
		        	if (localStorage.errstr == "Username or Password Incorrect") {
		        		chrome.browserAction.setTitle({title: "Error retrieving usage data.\nPlease confirm your username and password."});
		        		chrome.tabs.create({url:"xnet.options.html", selected:true});
		        	} else {
		        		chrome.browserAction.setTitle({title: "Error retrieving usage data.\nXnet Usage Monitor will retry every minute."});
		        		setTimeout(updateUsage, 1000 * 60);
		        	}

		        // Otherwise, if it's still okay...
		        } else if (localStorage.lastupdate) {

		        	localStorage.cap_original = parseFloat(localStorage.cap);

					// Overwrite the data cap if user has entered a custom cap
					if (localStorage.custom_cap_enable == 1 && parseFloat(localStorage.custom_cap) > 0) {
						localStorage.cap = localStorage.custom_cap;
					}

					// Add data to usage history database table (with a slight delay to ensure database has time to load if the extension's just loading up - possible Chrome bug)
					setTimeout(function(){
						openDb() && window.db.transaction(function(tx){
							var lastupdateSeconds = strtotime(localStorage.lastupdate);
							tx.executeSql('CREATE TABLE IF NOT EXISTS usageHistory (' +
											'lastupdate TEXT NOT NULL, ' +
											'lastupdateSeconds NUMERIC NOT NULL, ' +
											'bpc NUMERIC DEFAULT 0, ' +
											'rxlocal NUMERIC DEFAULT 0, ' +
											'txlocal NUMERIC DEFAULT 0, ' +
											'rxperiod1 NUMERIC DEFAULT 0, ' +
											'txperiod1 NUMERIC DEFAULT 0, ' +
											'total NUMERIC DEFAULT 0, ' +
											'cap NUMERIC DEFAULT 0, ' +
											'capCustom NUMERIC DEFAULT 0, ' +
											'planname TEXT DEFAULT "", ' +
											'freedataused TEXT DEFAULT "", ' +
											'plancharge NUMERIC DEFAULT 0, ' +
											'datacharge NUMERIC DEFAULT 0)');
							tx.executeSql('CREATE INDEX IF NOT EXISTS lastUpdateSecondsIndex ON usageHistory (lastUpdateSeconds)');
							tx.executeSql('DELETE FROM usageHistory WHERE lastupdateSeconds = ?', [lastupdateSeconds]);
							tx.executeSql('INSERT INTO usageHistory (lastupdate, lastupdateSeconds, bpc, rxlocal, txlocal, rxperiod1, txperiod1, total, cap, capCustom, planname, freedataused, plancharge, datacharge) '+
											'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
											[localStorage.lastupdate, lastupdateSeconds, localStorage.bpc, localStorage.rxlocal, localStorage.txlocal, localStorage.rxperiod1, localStorage.txperiod1, localStorage.total,
												localStorage.cap_original, localStorage.custom_cap_enable == 1 ? localStorage.custom_cap : 0, localStorage.planname, localStorage.freedataused, localStorage.plancharge, localStorage.datacharge]);
						}, function(e){
							console.log(e);
								webkitNotifications.createNotification(
								'green-x-48.png',
								'Xnet Usage Monitor has encountered a database error.',
								'Please check the extension\'s background console for details.'
							).show();
						});
					}, 1000);

			        // Set the icon's tooltip
			        updateTooltip();

			    // If we're still having problems, set tooltip and try updating in a minute
		        } else {
		        	chrome.browserAction.setTitle({title: "Error retrieving data"});
		        	setTimeout(updateUsage, 1000 * 60);
		        }
			},

			// If retrieval was unsuccessful, set an appropriate tooltip
			error: function(jqXHR, textStatus, errorThrown) {
				chrome.browserAction.setBadgeText({text:"!"});
				var newTitle;
				switch (textStatus) {
					case "error":
						newTitle = "Error retrieving usage data";
						break;
					case "timeout":
						newTitle = "Error retrieving usage data";
						break;
					case "abort":
						newTitle = "Error retrieving usage data (aborted)";
						break;
					case "parseerror":
						newTitle = "Error parsing usage data";
						break;
					default:
						newTitle = "Error retrieving usage data";
						break;
				}
				chrome.browserAction.setTitle({title:newTitle+(errorThrown.length ? ": "+errorThrown : "")+".\nXnet's usage server might be down, or your Internet connection may be offline.\nXnet Usage Monitor will keep retrying every minute."});

				// Try fetching again in a minute
				setTimeout(updateUsage, 1000 * 60);
			},

			// Tell popups to refresh info
			complete: function() {
				chrome.extension.sendRequest("render usage info");
			}
		});
	}
}

// If extension wants to update the usage, make it so
chrome.extension.onRequest.addListener(function(request) {
  	if (request == "update usage") {
  		updateUsage();
  	}
  	else if (request == "update tooltip") {
		updateTooltip();
  	}
});

// When the background is ready...
$(document).ready(function(){
	// If user has stored their credentials, enable the popup page
	if (localStorage.username && localStorage.password) {
		chrome.browserAction.setPopup({popup:"xnet.usage.html"});
	}

	// If popup page is not enabled, show the options page when user clicks the icon
	chrome.browserAction.onClicked.addListener(function(tab) {
		chrome.tabs.create({url:"xnet.options.html", selected:true});
	});

	// If user has not set their username, show the options page, otherwise update the usage
	if (!localStorage.username) {
		localStorage.newOptionsShown = 1;
		chrome.tabs.create({url:"xnet.options.html", selected:true});
	} else {
		if (!localStorage.newOptionsShown) {
			localStorage.newOptionsShown = 1;
			chrome.tabs.create({url:"xnet.options.html", selected:true});
		}
		updateUsage();
	}

	// Check for updates every 15 minutes
	setInterval(updateUsage, localStorage.ttl ? 1000 * localStorage.ttl : 1000 * 60 * 15);
});